package controllers

import (
    "git.oschina.net/hfwb/tianqi.git/tq/model"
    "fmt"
    "encoding/json"
    "strconv"
)

type Station struct {
	base
}

func (this *Station) List() {
    this.SetTitle("站点列表")
    this.menuList.Station.Open = true

    if list, err := model.NewStation().GetAll(); err != nil {
        this.AlertError(err.Error())
    } else {
        this.Data["list"] = list
    }
    this.TplName = "station.index.tpl"
}

func (this *Station) Edit() {
    this.SetTitle("站点修改")
    id, err := this.GetInt64("id")
    if err != nil {
        this.AlertError(err.Error())
    } else if station, err := model.NewStation().GetById(int(id)); err != nil {
        this.AlertError(err.Error())
    } else {
        if station == nil {
            station = new(model.Station)
        }
        if (this.Ctx.Request.Method == "POST") {
            if err := this.save(station); err != nil {
                this.AlertError(err.Error())
            } else {
                this.AlertSuccess("保存成功")
            }
        }
        this.Data["model"] = station
        fmt.Println(station)
    }
    this.TplName = "station.edit.tpl"
}

func (this *Station) Delete() {
    id, err := this.GetInt64("id")
    if err != nil {
        return
    }
    station, err := model.NewStation().GetById(int(id))
    if err != nil {
        return
    }
    if station != nil {
        station.Delete()
    }
    this.Redirect("/Station/List", 302)
}

func (this *Station) save(station *model.Station) error {
    station.Name = this.GetString("Name")
    station.Code = this.GetString("Code")
    station.CityName = this.GetString("CityName")
    station.Lat, _ = this.GetInt64("Lat")
    station.Long, _ = this.GetInt64("Long")
    station.Env = this.GetString("Env")
    station.ProvinceName = this.GetString("ProvinceName")
    station.Altitude = this.GetString("Altitude")
    monitors := make([]int, 5)
    for _, v := range this.GetStrings("Monitors") {
        if i, err := strconv.Atoi(v); err == nil {
            monitors[i] = 1
        }
    }
    bts, _ := json.Marshal(monitors)
    station.Monitor = string(bts)
    station.SetMonitors()
    return station.Save()
}
